// 从 localStorage 中获取数据
const students = JSON.parse(localStorage.getItem('socialStudents')) || [
    { id: 1, name: 'Alice', friends: [2], communities: [1], interests: ['reading'] },
    { id: 2, name: 'Bob', friends: [1], communities: [1], interests: ['badminton'] },
    { id: 3, name: 'Charlie', friends: [], communities: [], interests: ['badminton', 'swimming'] }
];

const communities = JSON.parse(localStorage.getItem('communities')) || [
    { id: 1, name: 'Community 1', members: [1, 2] }
];

// 1. 显示给定学生的所有朋友
document.getElementById('showFriends').addEventListener('click', function () {
    const studentName = document.getElementById('studentName').value || 'Alice';
    const student = students.find(s => s.name === studentName);
    const feedback = document.getElementById('showFriendsFeedback');
    
    if (student) {
        const friendNames = student.friends.map(friendId => 
            students.find(s => s.id === friendId).name
        );
        console.log(`${studentName}'s friends:`, friendNames);
        feedback.textContent = friendNames.length > 0 
            ? `${studentName}'s friends: ${friendNames.join(', ')}`
            : `${studentName} has no friends yet.`;
    } else {
        feedback.textContent = `Student ${studentName} not found.`;
    }
});

// 2. 添加新朋友
document.getElementById('addNewFriend').addEventListener('click', function () {
    const studentName = document.getElementById('studentName').value || 'Alice';
    const newFriendName = document.getElementById('newFriend').value;
    const student = students.find(s => s.name === studentName);
    const newFriend = students.find(s => s.name === newFriendName);
    const feedback = document.getElementById('addFriendFeedback');
    
    if (!student) {
        feedback.textContent = `Student ${studentName} not found.`;
        return;
    }
    
    if (!newFriend) {
        feedback.textContent = `Friend ${newFriendName} not found.`;
        return;
    }
    
    if (student.friends.includes(newFriend.id)) {
        feedback.textContent = `${newFriendName} is already a friend of ${studentName}.`;
        return;
    }
    
    // Add mutual friendship
    student.friends.push(newFriend.id);
    newFriend.friends.push(student.id);
    
    // 更新 localStorage
    localStorage.setItem('socialStudents', JSON.stringify(students));
    console.log(`New friend added to ${studentName}:`, newFriendName);
    feedback.textContent = `New friend added to ${studentName}: ${newFriendName}`;
});

// 3. 过滤连接
document.getElementById('filterConnections').addEventListener('click', function () {
    const studentName = document.getElementById('studentName').value || 'Alice';
    const criteria = document.getElementById('filterCriteria').value.toLowerCase();
    const student = students.find(s => s.name === studentName);
    const feedback = document.getElementById('filterFeedback');
    
    if (!student) {
        feedback.textContent = `Student ${studentName} not found.`;
        return;
    }
    
    const filteredFriends = student.friends
        .map(friendId => students.find(s => s.id === friendId))
        .filter(friend => 
            friend.interests && 
            friend.interests.some(interest => interest.toLowerCase().includes(criteria))
        );
    
    if (filteredFriends.length > 0) {
        const friendNames = filteredFriends.map(friend => friend.name);
        console.log(`Friends of ${studentName} who ${criteria}:`, friendNames);
        feedback.textContent = `Friends of ${studentName} interested in ${criteria}: ${friendNames.join(', ')}`;
    } else {
        feedback.textContent = `No friends of ${studentName} found interested in ${criteria}.`;
    }
});

// 4. 创建社区
document.getElementById('createCommunity').addEventListener('click', function () {
    const newCommunityName = document.getElementById('communityName').value;
    if (!newCommunityName) {
        document.getElementById('communityFeedback').textContent = 'Please enter a community name.';
        return;
    }
    
    const newCommunity = { 
        id: communities.length > 0 ? Math.max(...communities.map(c => c.id)) + 1 : 1,
        name: newCommunityName, 
        members: [] 
    };
    communities.push(newCommunity);
    
    // 更新 localStorage
    localStorage.setItem('communities', JSON.stringify(communities));
    console.log('New community created:', newCommunity.name);
    document.getElementById('communityFeedback').textContent = `New community created: ${newCommunity.name}`;
});

// 4. 加入社区
document.getElementById('joinCommunity').addEventListener('click', function () {
    const studentName = document.getElementById('studentName').value || 'Alice';
    const communityName = document.getElementById('communityName').value;
    const student = students.find(s => s.name === studentName);
    const feedback = document.getElementById('communityFeedback');
    
    if (!student) {
        feedback.textContent = `Student ${studentName} not found.`;
        return;
    }
    
    if (!communityName) {
        feedback.textContent = 'Please enter a community name.';
        return;
    }
    
    const community = communities.find(c => c.name === communityName);
    if (!community) {
        feedback.textContent = `Community ${communityName} not found.`;
        return;
    }
    
    if (student.communities.includes(community.id)) {
        feedback.textContent = `${studentName} is already a member of ${communityName}.`;
        return;
    }
    
    // Add student to community and vice versa
    student.communities.push(community.id);
    community.members.push(student.id);
    
    // 更新 localStorage
    localStorage.setItem('socialStudents', JSON.stringify(students));
    localStorage.setItem('communities', JSON.stringify(communities));
    console.log(`${studentName} joined community:`, community.name);
    feedback.textContent = `${studentName} joined community: ${community.name}`;
});

// 5. 查找社区间的桥梁
document.getElementById('findBridges').addEventListener('click', function () {
    const feedback = document.getElementById('bridgesFeedback');
    
    // Find students who are members of more than one community
    const bridgeStudents = students.filter(student => 
        student.communities && student.communities.length > 1
    );
    
    if (bridgeStudents.length === 0) {
        feedback.textContent = 'No bridge students found between communities.';
        return;
    }
    
    // For each bridge student, find which communities they connect
    const bridges = bridgeStudents.map(student => {
        const connectedCommunities = student.communities
            .map(comId => communities.find(c => c.id === comId).name)
            .join(' and ');
        return `${student.name} connects ${connectedCommunities}`;
    });
    
    console.log('Bridges between communities:', bridges);
    feedback.textContent = 'Bridges between communities:\n' + bridges.join('\n');
});

// 添加新学生
document.getElementById('addNewStudent').addEventListener('click', function () {
    const newStudentName = document.getElementById('newStudentName').value;
    const feedback = document.getElementById('addStudentFeedback');
    
    if (!newStudentName) {
        feedback.textContent = 'Please enter a student name.';
        return;
    }
    
    if (students.some(s => s.name === newStudentName)) {
        feedback.textContent = `Student ${newStudentName} already exists.`;
        return;
    }
    
    const newStudent = { 
        id: students.length > 0 ? Math.max(...students.map(s => s.id)) + 1 : 1,
        name: newStudentName,
        friends: [],
        communities: [],
        interests: []
    };
    
    students.push(newStudent);
    localStorage.setItem('socialStudents', JSON.stringify(students));
    feedback.textContent = `New student added: ${newStudentName}`;
});